import React from "react";
import {Divider, Select} from "antd";
import {observer} from "mobx-react";
import environmentStore from "../store/environmentStore";
const {Option} = Select;
import "./envStyle.scss"
import EnvSettingModel from "./EnvSettingModel";
import envServerStore from "../store/envServerStore";
import envVariableStore from "../store/envVariableStore";

/**
 * 环境选择
 */
const EnvSelect = (props) => {
    const { findEnvironmentList, environmentList,setSelectEnvInfo,selectEnvInfo } = environmentStore;
    const {findEnvServerList} = envServerStore
    const {findEnvVariableList} = envVariableStore;

    let workspaceId=localStorage.getItem("workspaceId")
 
    /**
     * 选择测试环境 input框呈现相应的地址
     */
    const onSelectChange =async (id) => {

        let serverList = []
        let variableList = []

        if(id){
            //设置环境服务器列表
            let envServerList =await findEnvServerList({envId:id})
            if(envServerList&&envServerList.length>0){
                serverList=envServerList
            }

            //设置变量
            let envVariableList = await findEnvVariableList({envId:id})
            if(envVariableList&&envVariableList.length>0){
                variableList=envVariableList
            }
        }

        let info = {
            envId:id,
            serverList:serverList,
            variableList:variableList
        }

        setSelectEnvInfo(info)
    }

    /**
     * 渲染环境选项
     */
    const showOption = (data) => {
        return data && data.map(item => {
            return (
                <Option key={item.id} value={item.id}>
                    <div className="pi-env-option">
                        <span>{item.name}</span>
                    </div>
                </Option>
            )
        })
    }

    const onDropdownVisibleChange = async () => {
        await findEnvironmentList({workspaceId: workspaceId})
    }

    return (
        <Select
            bordered={false}
            className="ws-select-box"
            placeholder="请选择环境"
            onSelect={onSelectChange}
            // value={selectedEnv}
            defaultValue={selectEnvInfo.envId}
            onDropdownVisibleChange={onDropdownVisibleChange}
            dropdownRender={menu => (
                <div className="pi-env-dropdown">
                    <div className="env-list-container">
                        {menu}
                    </div>
                    <Divider style={{ margin: '8px 0' }} />
                    <div className="env-setting-link">
                        <EnvSettingModel name="环境配置" />
                    </div>
                </div>
            )}
        >
            <Option value={null}>无</Option>
            {showOption(environmentList)}
        </Select>
    )
}

export default observer(EnvSelect);